'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';

interface MediaFile {
  id: string;
  name: string;
  originalName: string;
  type: 'image' | 'video' | 'document';
  size: number;
  url: string;
  uploadDate: string;
  category?: string;
}

export default function MediaPage() {
  const [mediaFiles, setMediaFiles] = useState<MediaFile[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchMediaFiles();
  }, []);

  const fetchMediaFiles = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/admin/media');
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setMediaFiles(data.data);
        }
      }
    } catch (error) {
      console.error('Error fetching media files:', error);
    } finally {
      setLoading(false);
    }
  };

  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [filterType, setFilterType] = useState<'all' | 'image' | 'video' | 'document'>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [uploadProgress, setUploadProgress] = useState<number | null>(null);

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    const formData = new FormData();
    Array.from(files).forEach(file => {
      formData.append('files', file);
    });

    try {
      setUploadProgress(0);
      
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      });
      
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setUploadProgress(100);
          setTimeout(() => {
            setUploadProgress(null);
            fetchMediaFiles(); // 重新获取文件列表
          }, 1000);
        }
      } else {
        setUploadProgress(null);
        alert('上传失败，请重试');
      }
    } catch (error) {
      console.error('Error uploading files:', error);
      setUploadProgress(null);
      alert('上传失败，请重试');
    }

    // 清空input
    e.target.value = '';
  };

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个文件吗？')) {
      try {
        const response = await fetch(`/api/admin/media?filename=${id}`, {
          method: 'DELETE'
        });
        
        if (response.ok) {
          await fetchMediaFiles();
          setSelectedFiles(selectedFiles.filter(fileId => fileId !== id));
        } else {
          alert('删除失败，请重试');
        }
      } catch (error) {
        console.error('Error deleting file:', error);
        alert('删除失败，请重试');
      }
    }
  };

  const handleBatchDelete = async () => {
    if (confirm(`确定要删除选中的 ${selectedFiles.length} 个文件吗？`)) {
      try {
        // 逐个删除文件
        for (const fileId of selectedFiles) {
          await fetch(`/api/admin/media?filename=${fileId}`, {
            method: 'DELETE'
          });
        }
        
        await fetchMediaFiles();
        setSelectedFiles([]);
      } catch (error) {
        console.error('Error batch deleting files:', error);
        alert('批量删除失败，请重试');
      }
    }
  };

  const handleSelectAll = () => {
    if (selectedFiles.length === filteredFiles.length) {
      setSelectedFiles([]);
    } else {
      setSelectedFiles(filteredFiles.map(file => file.id));
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getFileIcon = (type: string) => {
    switch (type) {
      case 'image':
        return '🖼️';
      case 'video':
        return '🎥';
      case 'document':
        return '📄';
      default:
        return '📁';
    }
  };

  const filteredFiles = mediaFiles.filter(file => {
    const matchesType = filterType === 'all' || file.type === filterType;
    const matchesSearch = file.originalName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         file.category?.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesType && matchesSearch;
  });

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">媒体库</h1>
          <p className="text-gray-600 mt-1">管理上传的图片、视频和文档文件</p>
        </div>
        <label className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer">
          📁 上传文件
          <input
            type="file"
            multiple
            accept="image/*,video/*,.pdf,.doc,.docx"
            onChange={handleFileUpload}
            className="hidden"
          />
        </label>
      </div>

      {/* Upload Progress */}
      {uploadProgress !== null && (
        <div className="bg-white rounded-lg border p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium">正在上传...</span>
            <span className="text-sm text-gray-500">{uploadProgress}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-blue-600 h-2 rounded-full transition-all duration-300"
              style={{ width: `${uploadProgress}%` }}
            />
          </div>
        </div>
      )}

      {/* Stats and Filters */}
      <div className="bg-white rounded-lg border p-4">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">
              {mediaFiles.length}
            </div>
            <div className="text-sm text-gray-600">总文件数</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {mediaFiles.filter(f => f.type === 'image').length}
            </div>
            <div className="text-sm text-gray-600">图片</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">
              {mediaFiles.filter(f => f.type === 'video').length}
            </div>
            <div className="text-sm text-gray-600">视频</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-yellow-600">
              {mediaFiles.filter(f => f.type === 'document').length}
            </div>
            <div className="text-sm text-gray-600">文档</div>
          </div>
        </div>

        {/* Controls */}
        <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
          <div className="flex flex-col md:flex-row gap-4 items-start md:items-center">
            {/* Search */}
            <div>
              <input
                type="text"
                placeholder="搜索文件..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="border border-gray-300 rounded-lg px-3 py-2 w-64 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            {/* Filter */}
            <div>
              <select
                value={filterType}
                onChange={(e) => setFilterType(e.target.value as any)}
                className="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="all">所有类型</option>
                <option value="image">🖼️ 图片</option>
                <option value="video">🎥 视频</option>
                <option value="document">📄 文档</option>
              </select>
            </div>

            {/* View Mode */}
            <div className="flex rounded-lg border border-gray-300 overflow-hidden">
              <button
                onClick={() => setViewMode('grid')}
                className={`px-3 py-2 text-sm ${
                  viewMode === 'grid' 
                    ? 'bg-blue-600 text-white' 
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                }`}
              >
                🔲 网格
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`px-3 py-2 text-sm ${
                  viewMode === 'list' 
                    ? 'bg-blue-600 text-white' 
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                }`}
              >
                📝 列表
              </button>
            </div>
          </div>

          {/* Batch Actions */}
          {selectedFiles.length > 0 && (
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-600">
                已选择 {selectedFiles.length} 个文件
              </span>
              <button
                onClick={handleBatchDelete}
                className="px-3 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm"
              >
                🗑️ 批量删除
              </button>
            </div>
          )}
        </div>

        {filteredFiles.length > 0 && (
          <div className="mt-4 flex items-center">
            <button
              onClick={handleSelectAll}
              className="text-sm text-blue-600 hover:text-blue-800"
            >
              {selectedFiles.length === filteredFiles.length ? '取消全选' : '全选'}
            </button>
          </div>
        )}
      </div>

      {/* File List */}
      <div className="bg-white rounded-lg border">
        {filteredFiles.length === 0 ? (
          <div className="p-8 text-center text-gray-500">
            {mediaFiles.length === 0 ? '暂无文件，点击上传文件按钮开始' : '没有找到匹配的文件'}
          </div>
        ) : viewMode === 'grid' ? (
          /* Grid View */
          <div className="p-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4">
            {filteredFiles.map((file) => (
              <div key={file.id} className="group relative border rounded-lg overflow-hidden hover:shadow-md transition-shadow">
                <div className="aspect-square bg-gray-100 flex items-center justify-center relative">
                  {file.type === 'image' ? (
                    <img
                      src={file.url}
                      alt={file.originalName}
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        e.currentTarget.src = '';
                      }}
                    />
                  ) : (
                    <div className="text-4xl">
                      {getFileIcon(file.type)}
                    </div>
                  )}
                  
                  {/* Selection Checkbox */}
                  <div className="absolute top-2 left-2">
                    <input
                      type="checkbox"
                      checked={selectedFiles.includes(file.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedFiles([...selectedFiles, file.id]);
                        } else {
                          setSelectedFiles(selectedFiles.filter(id => id !== file.id));
                        }
                      }}
                      className="w-4 h-4"
                    />
                  </div>

                  {/* Actions */}
                  <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                      onClick={() => handleDelete(file.id)}
                      className="bg-red-600 text-white p-1 rounded text-xs hover:bg-red-700"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
                
                <div className="p-2">
                  <div className="text-xs font-medium text-gray-900 truncate" title={file.originalName}>
                    {file.originalName}
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    {formatFileSize(file.size)}
                  </div>
                  {file.category && (
                    <div className="text-xs text-blue-600 mt-1 truncate">
                      {file.category}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          /* List View */
          <div className="divide-y divide-gray-200">
            {filteredFiles.map((file) => (
              <div key={file.id} className="p-4 hover:bg-gray-50 flex items-center space-x-4">
                <input
                  type="checkbox"
                  checked={selectedFiles.includes(file.id)}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setSelectedFiles([...selectedFiles, file.id]);
                    } else {
                      setSelectedFiles(selectedFiles.filter(id => id !== file.id));
                    }
                  }}
                  className="w-4 h-4"
                />
                
                <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center text-lg">
                  {file.type === 'image' ? (
                    <img
                      src={file.url}
                      alt={file.originalName}
                      className="w-full h-full object-cover rounded-lg"
                      onError={(e) => {
                        e.currentTarget.style.display = 'none';
                        (e.currentTarget.nextElementSibling as HTMLElement)!.style.display = 'block';
                      }}
                    />
                  ) : (
                    getFileIcon(file.type)
                  )}
                </div>
                
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-gray-900 truncate">
                    {file.originalName}
                  </div>
                  <div className="text-sm text-gray-500 mt-1">
                    {formatFileSize(file.size)} • {file.uploadDate}
                    {file.category && ` • ${file.category}`}
                  </div>
                </div>
                
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => window.open(file.url, '_blank')}
                    className="text-blue-600 hover:text-blue-800 p-1"
                  >
                    👁️
                  </button>
                  <button
                    onClick={() => handleDelete(file.id)}
                    className="text-red-600 hover:text-red-800 p-1"
                  >
                    🗑️
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}